package com.it.sun.easychat.common.context;

import cn.hutool.core.lang.Assert;
import com.it.sun.esaychat.user.exception.UserNotFoundException;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Optional;

/**
 * @author sunmannian
 * @ClassName com.it.sun.easychat.common.context.RequestContext
 * @Date 2020/6/2 19:51
 * @Version V1.0
 * Description  <请求上下文信息>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/6/2
 */
public class RequestContext {

    public static Current getCurrent() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Current current = (Current) requestAttributes.getAttribute
                (Current.CURRENT_NAME, RequestAttributes.SCOPE_SESSION);
        Assert.notNull(current, "为获取到当前用户信息");
        return current;
    }


    /**
     * <描述方法功能>
     * <获取当前用户id>
     *
     * @param
     * @return java.lang.String
     * @Author sunmannian
     * @Description
     * @Date 2020/6/2 20:50
     **/
    public static String getCurrentUserId() {
        return Optional.ofNullable(getCurrent().getUser()).
                orElseThrow(UserNotFoundException::new).getId();
    }
}
